<script setup>
import { defineOptions, ref } from 'vue'
import { copy2Clipboard } from '@/utils/commonUtil.js'
import { ElMessage } from 'element-plus'
import { beautifySQL } from '@/utils/sqlParser.js'

defineOptions({
  name: 'MybatisLogFormatter'
})
const data = ref({
  row: 10,
  leftStr: '',
  rightStr: '',
  sql: '',
  paramArr: []
})
const placeholder = {
  left: `==> Preparing:select *from user where id=?\n==> Parameters: 1(Integer)`,
  right: `SELECT \n *\nFROM user \nWHERE id = 1`
}
const parseLog2SqlV2 = () => {
  if (data.value.leftStr.includes("Preparing:")) {
    const strArr = data.value.leftStr
        .replaceAll("==>", "")
        .split("Parameters:");
    const params = strArr[1];
    const containsSqlStr = strArr[0]
    const sqlArr = containsSqlStr.split("Preparing:")
    data.value.sql = sqlArr[sqlArr.length - 1]
    data.value.paramArr = params.split(",")
    while (data.value.sql.includes('?')) {
      data.value.paramArr.forEach(item => {
        let afterStr = item.substring(0, item.indexOf('('))
        if (item.includes("(LocalDateTime)") ||
            item.includes("(Date)") ||
            item.includes("(LocalTime)") ||
            item.includes("(LocalDate)") ||
            item.includes("(Timestamp)") ||
            item.includes("(String)")
        ) {
          afterStr = `'${afterStr}'`
        }
        data.value.sql = data.value.sql.replace('?', afterStr)
      })
    }
    data.value.rightStr = beautifySQL(data.value.sql)
  } else {
    ElMessage.error('请填写包含Preparing:完整MybatisLog')
  }
}
</script>
<template>
  <div class="container">
    <el-input
        type="textarea"
        class="textarea left custom-input"
        :row="data.row"
        v-model="data.leftStr"
        :placeholder="placeholder.left"
    />
    <el-input
        type="textarea"
        class="textarea right custom-input"
        :row="data.row"
        v-model="data.rightStr"
        :placeholder="placeholder.right"
    />
  </div>
  <el-footer>
    <el-button @click="parseLog2SqlV2" type="primary">
      转换
    </el-button>
    <el-button @click="copy2Clipboard(data)" type="primary">
      复制
    </el-button>
  </el-footer>
</template>
<style></style>
